<?php

session_start(); // Starts the session.

// Set global object with config and functions
require_once ('_includes/class_includes.php');

//check if buffered content is required
if(@$usebufferedcontent == null){
    $usebufferedcontent = false;
}

//Create global configuration object
$PACTS_cfg = new PactsCfg();
$PACTS_cfg->init(false,$usebufferedcontent);

$bDatabaseStatusOk = $PACTS_cfg->checkSqlSetup(false,false);

if ($bDatabaseStatusOk){
    //echo "No Error";
} else {
    echo 'There appears to be an problem with the database setup. Please click <a href="index.php?view=SetupSqlTables&type=setup">here</a> to fix.'."\n";
    exit;
}

$bUserAccountsOk = $PACTS_cfg->checkUserAccounts(false);

if (!$bUserAccountsOk){
    //echo "No Error";
} else {
    echo 'There appears to be an problem with the users accounts. Please click <a href="index.php?view=SetupSqlTables&type=setup">here</a> to fix.'."\n";
    exit;
}


/*
 *
echo"sess var<pre>";
print_r(@$_SESSION);
echo"</pre>";
exit(0);
*/

if (@$_SESSION['logged'] == 1 && @$_SESSION['username'] !="")
{ // User is already logged in.
    if (@$_COOKIE['ReferringPage'] != null 
        &&  !(strpos(strtolower($_COOKIE['ReferringPage']),"logout") > 0)

        )
    {
        $PageToRedirectTo = @$_COOKIE['ReferringPage'];
        setcookie("ReferringPage", "", time()-60);  /* expire in 1 hour */

        header("Location: ".@$_COOKIE['ReferringPage']); // Goes to main page.

    } else
    {
        header("Location: index.php?view=Home"); // Goes to main page.

    }
    exit(); // Stops the rest of the script.
} else
{

    if (!isset($_POST['submit']))
    { // The form has not been submitted.


/*
    echo '<pre>';
    print_r(@$_COOKIE['ReferringPage']);
    print_r(@$_SERVER);
    print_r(@$_POST);
    print_r(@$_GET);
    echo '</pre>';
    echo '<p/>';
*/

        if ((@$_COOKIE['ReferringPage'] != null || @$_COOKIE['ReferringPostData'] != null ) && !(strpos(strtolower(@$_COOKIE['ReferringPostData']),"view=logout") > 0) && strpos(strtolower(@$_COOKIE['ReferringPostData']),"view=") > 0)
        {
            $PACTS_cfg->URLmessage = 'Note: Previous action has not been lost, just login again and the action will be performed'; // Stops the script with an error message.
        }

        //include page content
        include(substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1).'_content/'.substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'],"/")+1));

    }
    else
    {

//        require_once ('_includes/PACTS_config_variables.php');
//        require_once ('_includes/PACTS_config.php');
        $PACTS_cfg = new PactsCfg();

        $username = $PACTS_cfg->cleanformdata($_POST['username']);
        $password = md5($_POST['password']); // Encrypts the password.

        $q = mysql_query("SELECT * FROM `Users` WHERE username = '$username' AND pw = '$password'",$PACTS_cfg->dblink) or die (mysql_error()); // mySQL query
        $r = mysql_num_rows($q); // Checks to see if anything is in the db.

        if ($r == 1)
        { // There is something in the db. The username/password match up.
            $db_pass = mysql_fetch_array($q, MYSQL_ASSOC);

            // check if user is enabled
            if (strtolower($db_pass['Enabled']) =="n"){
                // // Invalid username/password.
                //clear details
                $username = "";
                $password = "";
                $PACTS_cfg->URLmessage = "Account is not enabled!"; // Stops the script with an error message.
                //
                //include page content
                include(substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1).'_content/'.substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'],"/")+1));
                exit;
            }



            $_SESSION['logged'] = 1; // Sets the session.

            $_SESSION['username'] = $username;
            $_SESSION['UserId'] = $db_pass['id'];
            $_SESSION['last_login'] = $db_pass['LastLoginTMS'];
            $_SESSION['LoginCount'] = (int) $db_pass['LoginCount'] + 1;

            $tmp_pass = mysql_query("UPDATE Users SET LastLoginTMS = now(), LoginCount = ".$_SESSION['LoginCount']." WHERE username = '".$_SESSION['username']."'");
            mysql_close($PACTS_cfg->dblink); // Closes the connection.
/*
            echo "<pre>";
            print_r($_SESSION);
            echo "</pre>";
*/



            if (@$_COOKIE['ReferringPage'] != null
                    &&  !(strpos(strtolower($_COOKIE['ReferringPage']),"logout") > 0)
                ){
                $PageToRedirectTo = @$_COOKIE['ReferringPage'];
                setcookie("ReferringPage", "", time()-60);  /* expire in 1 hour */


                header("Location: ".@$_COOKIE['ReferringPage']); // Goes to main page.

            } else {
                header("Location: index.php?view=Home"); // Goes to main page.

            }


            exit(); // Stops the rest of the script.
        }
        else
        { 
            // // Invalid username/password.
            $PACTS_cfg->URLmessage = "Incorrect username/password!"; // Stops the script with an error message.
            //
            //include page content
            include(substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'],"/")+1).'_content/'.substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'],"/")+1));

        }
    }
}
?>